// index/pages/memberDetail/memberDetail.js
// 导入用户管理工具类
const userManager = require('../../../utils/userManager.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 用户信息
    userInfo: {
      username: '',
      phone: '',
      avatar: '/images/default-avatar.png',
      userType: '普通用户'
    },
    
    // 用户档案数据
    userProfile: null,
    memberDaysRemaining: 0,
    isVip: false,
    isLoggedIn: false,
    
    // 会员类型
    membershipType: 'questionBank', // questionBank 或 fullSite
    
    // 专属题库会员套餐
    membershipOptions: [
      {
        id: 1,
        duration: '1年',
        currentPrice: '240',
        originalPrice: '270',
        price: 240,
        isSelected: true,
        isValue: true
      },
      {
        id: 2,
        duration: '6个月',
        currentPrice: '120',
        originalPrice: '150',
        price: 120,
        isSelected: false,
        isValue: false
      },
      {
        id: 3,
        duration: '3个月',
        currentPrice: '60',
        originalPrice: '90',
        price: 60,
        isSelected: false,
        isValue: false
      }
    ],
    
    // 全站会员套餐
    fullSiteOptions: [
      {
        id: 1,
        duration: '1年',
        currentPrice: '300',
        originalPrice: '360',
        price: 300,
        isSelected: true,
        isValue: true
      },
      {
        id: 2,
        duration: '6个月',
        currentPrice: '180',
        originalPrice: '240',
        price: 180,
        isSelected: false,
        isValue: false
      },
      {
        id: 3,
        duration: '3个月',
        currentPrice: '90',
        originalPrice: '150',
        price: 90,
        isSelected: false,
        isValue: false
      }
    ],
    
    // 题库信息
    questionBanks: [
      {
        title: '2025考研政治',
        main: '1000题',
        sub: '基础强化',
        courseName: '2024水利工程物理研究',
        tags: ['物理', '题库分类', '名词解释'],
        questionCount: '9道题'
      },
      {
        title: '2025考研政治',
        main: '1000题',
        sub: '基础强化',
        courseName: '2024水利工程物理研究',
        tags: ['物理', '题库分类', '名词解释'],
        questionCount: '9道题'
      }
    ],
    
    // 会员权益
    benefits: [
      { icon: '💎', text: '超级会员价' },
      { icon: '💰', text: '每月优惠券' },
      { icon: '📦', text: '运费券礼包' },
      { icon: '🪙', text: '返双倍积分' },
      { icon: '⭐', text: '会员内购价' },
      { icon: '🎁', text: '专属礼品卡' },
      { icon: '💵', text: '更高返现' },
      { icon: '🎧', text: '专属客服' }
    ]
  },

  /**
   * 切换会员类型
   */
  switchMembershipType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      membershipType: type
    });
  },

  /**
   * 选择会员套餐
   */
  selectMembershipOption(e) {
    const index = e.currentTarget.dataset.index;
    
    if (this.data.membershipType === 'questionBank') {
      const options = this.data.membershipOptions.map((option, i) => {
        option.isSelected = i === index;
        return option;
      });
      
      this.setData({
        membershipOptions: options
      });
    } else {
      const options = this.data.fullSiteOptions.map((option, i) => {
        option.isSelected = i === index;
        return option;
      });
      
      this.setData({
        fullSiteOptions: options
      });
    }
  },

  /**
   * 立即开通
   */
  activateMembership() {
    const options = this.data.membershipType === 'questionBank' ? this.data.membershipOptions : this.data.fullSiteOptions;
    const selectedOption = options.find(option => option.isSelected);
    
    wx.showModal({
      title: '确认开通',
      content: `确定要开通${this.data.membershipType === 'questionBank' ? '专属题库会员' : '全站会员'}吗？\n套餐：${selectedOption.duration}\n价格：¥${selectedOption.currentPrice}`,
      confirmText: '确认支付',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.processPayment();
        } else {
          // 用户取消，创建待支付订单
          this.processCancelPayment();
        }
      }
    });
  },

  /**
   * 处理支付
   */
  processPayment() {
    wx.showLoading({
      title: '支付中...'
    });
    
    // 获取选中的套餐信息
    const options = this.data.membershipType === 'questionBank' ? this.data.membershipOptions : this.data.fullSiteOptions;
    const selectedOption = options.find(option => option.isSelected);
    
    // 确定questionBankId
    const questionBankId = this.data.membershipType === 'questionBank' ? 34 : 35;
    
    // 创建OrderInfo对象
    const orderInfo = {
      userId: userManager.getUserId(),
      questionBankId: questionBankId,
      amount: selectedOption.price,
      orderNo: this.generateOrderOn(),
      status: 'PAID'  // 确定支付时状态为PAID
    };
    
    console.log('=== 开始调用新增订单接口 ===');
    console.log('OrderInfo对象:', orderInfo);
    
    // 调用新增订单接口
    const { http } = require('../../../utils/http');
    
    http.post('/points/info', orderInfo)
      .then(res => {
        console.log('新增订单接口响应:', res);
        
        if (res && res.code === 200) {
          // 订单创建成功，继续调用会员更新接口
          this.updateMemberType();
        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.msg || '订单创建失败',
            icon: 'none',
            duration: 2000
          });
        }
      })
      .catch(err => {
        console.error('新增订单接口调用失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '订单创建失败',
          icon: 'none',
          duration: 2000
        });
      });
  },

  /**
   * 处理取消支付
   */
  processCancelPayment() {
    wx.showLoading({
      title: '处理中...'
    });
    
    // 获取选中的套餐信息
    const options = this.data.membershipType === 'questionBank' ? this.data.membershipOptions : this.data.fullSiteOptions;
    const selectedOption = options.find(option => option.isSelected);
    
    // 确定questionBankId
    const questionBankId = this.data.membershipType === 'questionBank' ? 34 : 35;
    
    // 创建OrderInfo对象（待支付状态）
    const orderInfo = {
      userId: userManager.getUserId(),
      questionBankId: questionBankId,
      amount: selectedOption.price,
      orderNo: this.generateOrderOn(),
      status: 'PENDING'  // 取消时状态为PENDING
    };
    
    console.log('=== 开始调用新增订单接口（待支付） ===');
    console.log('OrderInfo对象:', orderInfo);
    
    // 调用新增订单接口
    const { http } = require('../../../utils/http');
    
    http.post('/points/info', orderInfo)
      .then(res => {
        console.log('新增订单接口响应（待支付）:', res);
        wx.hideLoading();
        
        if (res && res.code === 200) {
          wx.showToast({
            title: '订单已创建，请及时支付',
            icon: 'success',
            duration: 2000
          });
          
          // 延迟跳转到订单页面
          setTimeout(() => {
            wx.navigateTo({
              url: '/my/pages/Order/Order',
              success: () => {
                console.log('跳转到订单页面成功');
              },
              fail: (err) => {
                console.error('跳转失败:', err);
                wx.showToast({
                  title: '跳转失败',
                  icon: 'none',
                  duration: 2000
                });
              }
            });
          }, 2000);
        } else {
          wx.showToast({
            title: res.msg || '订单创建失败',
            icon: 'none',
            duration: 2000
          });
        }
      })
      .catch(err => {
        console.error('新增订单接口调用失败（待支付）:', err);
        wx.hideLoading();
        wx.showToast({
          title: '订单创建失败',
          icon: 'none',
          duration: 2000
        });
      });
  },

  /**
   * 更新会员类型
   */
  updateMemberType() {
    // 计算新的会员类型和到期时间
    const { newMemberType, newMemberExpire } = this.calculateNewMembership();
    
    // 准备请求数据
    const requestData = {
      userId: userManager.getUserId(),
      memberType: newMemberType,
      memberExpire: newMemberExpire
    };
    
    console.log('=== 开始调用会员更新接口 ===');
    console.log('请求数据:', requestData);
    
    // 调用后端接口
    const { http } = require('../../../utils/http');
    
    http.put('/points/profile/updateMemberType', requestData)
      .then(res => {
        console.log('会员更新接口响应:', res);
        wx.hideLoading();
        
        if (res && res.code === 200) {
          wx.showToast({
            title: '开通成功！',
            icon: 'success',
            duration: 2000
          });
          
          // 延迟跳转到支付结果页面
          setTimeout(() => {
            wx.navigateTo({
              url: '/index/pages/paymentResult/paymentResult',
              success: () => {
                console.log('跳转到支付结果页面成功');
              },
              fail: (err) => {
                console.error('跳转失败:', err);
                wx.showToast({
                  title: '跳转失败',
                  icon: 'none',
                  duration: 2000
                });
              }
            });
          }, 2000);
        } else {
          wx.showToast({
            title: res.msg || '开通失败',
            icon: 'none',
            duration: 2000
          });
        }
      })
      .catch(err => {
        console.error('会员更新接口调用失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '开通失败',
          icon: 'none',
          duration: 2000
        });
      });
  },

  /**
   * 生成随机订单号
   */
  generateOrderOn() {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 10000);
    return `ORDER${timestamp}${random}`;
  },

  /**
   * 计算新的会员类型和到期时间
   */
  calculateNewMembership() {
    const currentMemberType = this.data.userProfile ? this.data.userProfile.memberType : null;
    const currentMemberExpire = this.data.userProfile ? this.data.userProfile.memberExpire : null;
    const selectedMembershipType = this.data.membershipType;
    const options = this.data.membershipType === 'questionBank' ? this.data.membershipOptions : this.data.fullSiteOptions;
    const selectedOption = options.find(option => option.isSelected);
    
    // 确定新的会员类型
    let newMemberType;
    if (selectedMembershipType === 'questionBank') {
      newMemberType = 'EXCLUSIVE';
    } else {
      newMemberType = 'GLOBAL';
    }
    
    // 计算新的到期时间
    let newMemberExpire;
    const now = new Date();
    
    // 根据选择的套餐计算时长（天数）
    let durationDays = 0;
    if (selectedOption.duration === '1年') {
      durationDays = 365;
    } else if (selectedOption.duration === '6个月') {
      durationDays = 180;
    } else if (selectedOption.duration === '3个月') {
      durationDays = 90;
    }
    
    if (currentMemberType === null) {
      // 新用户，从当前时间开始计算
      newMemberExpire = new Date(now.getTime() + durationDays * 24 * 60 * 60 * 1000);
    } else {
      // 现有会员，从原到期时间开始计算
      const baseDate = currentMemberExpire ? new Date(currentMemberExpire) : now;
      newMemberExpire = new Date(baseDate.getTime() + durationDays * 24 * 60 * 60 * 1000);
    }
    
    console.log('计算新的会员信息:', {
      currentMemberType,
      currentMemberExpire,
      selectedMembershipType,
      selectedOption: selectedOption.duration,
      newMemberType,
      newMemberExpire: newMemberExpire.toISOString()
    });
    
    return {
      newMemberType,
      newMemberExpire: newMemberExpire.toISOString()
    };
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('会员详情页面加载');
    
    // 检查登录状态
    this.checkLoginStatus();
    
    // 加载用户基本信息
    this.loadUserInfo();
    
    // 加载用户档案信息
    this.loadUserProfile();
    
    // 如果有传入的参数，可以在这里处理
    if (options.type) {
      this.setData({
        membershipType: options.type
      });
    }
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const currentUser = userManager.getCurrentUser();
    
    if (currentUser) {
      this.setData({
        isLoggedIn: true
      });
      console.log('用户已登录');
    } else {
      this.setData({
        isLoggedIn: false
      });
      console.log('用户未登录');
    }
  },

  /**
   * 加载用户基本信息
   */
  loadUserInfo() {
    console.log('=== 开始加载用户基本信息 ===');
    
    const currentUser = userManager.getCurrentUser();
    console.log('currentUser:', currentUser);
    
    if (currentUser && currentUser.userInfo) {
      const userInfo = currentUser.userInfo;
      console.log('原始用户信息:', userInfo);
      
      // 更新用户信息 - 尝试多种可能的字段名
      const updatedUserInfo = {
        username: userInfo.userName || userInfo.username || userInfo.nickName || userInfo.nickname || userInfo.name || '用户',
        phone: userInfo.phone || userInfo.mobile || userInfo.telephone || userInfo.tel || userInfo.phonenumber || '未设置',
        avatar: userInfo.avatar || userInfo.avatarUrl || userInfo.headimgurl || userInfo.headImgUrl || '/images/default-avatar.png',
        userType: '普通用户'
      };
      
      this.setData({
        userInfo: updatedUserInfo
      });
      
      console.log('用户基本信息加载成功:', updatedUserInfo);
    } else {
      console.log('未找到用户信息，使用默认值');
      // 使用默认值
      const defaultUserInfo = {
        username: '用户',
        phone: '未设置',
        avatar: '/images/default-avatar.png',
        userType: '普通用户'
      };
      
      this.setData({
        userInfo: defaultUserInfo
      });
      
      console.log('使用默认用户信息:', defaultUserInfo);
    }
  },

  /**
   * 加载用户档案信息
   */
  loadUserProfile() {
    // 获取用户ID
    const userId = userManager.getUserId();
    console.log('=== 会员详情页面用户档案获取 ===');
    console.log('userManager.getUserId() 返回值:', userId);
    
    if (!userId) {
      console.log('用户ID为空，无法获取档案信息');
      return;
    }

    console.log('获取到用户ID:', userId);
    console.log('=== 开始调用用户档案接口 ===');

    // 调用用户档案接口
    const { http } = require('../../../utils/http');
    
    // 使用正确的接口路径
    const apiUrl = `/points/profile/selectSysUserProfileByUserId?userId=${userId}`;
    console.log('调用接口:', apiUrl);
    
    http.get(apiUrl)
      .then(res => {
        console.log('获取用户档案完整响应:', res);
        
        // 检查响应结构
        if (res && res.code === 200 && res.data) {
          const profile = res.data;
          console.log('解析到的用户档案:', profile);
          
          // 提取需要的字段：memberType 和 memberExpire
          const memberType = profile.memberType;
          const memberExpire = profile.memberExpire;
          
          // 计算会员剩余天数
          const daysRemaining = this.calculateDaysRemaining(memberExpire);
          
          // 判断是否为会员
          const isVip = memberType === 'EXCLUSIVE' || memberType === 'GLOBAL';
          
          // 更新页面数据
          this.setData({
            userProfile: profile,
            memberDaysRemaining: daysRemaining,
            isVip: isVip
          });
          
          // 如果用户档案中有用户信息，也更新用户基本信息
          if (profile.sysYouYouUser) {
            const sysUser = profile.sysYouYouUser;
            const updatedUserInfo = {
              username: sysUser.nickName || sysUser.userName || sysUser.username || this.data.userInfo.username || '用户',
              phone: sysUser.phonenumber || sysUser.phone || sysUser.mobile || sysUser.telephone || this.data.userInfo.phone || '未设置',
              avatar: sysUser.avatar || sysUser.avatarUrl || this.data.userInfo.avatar || '/images/default-avatar.png',
              userType: '普通用户'
            };
            
            this.setData({
              userInfo: updatedUserInfo
            });
            
            console.log('从用户档案更新用户信息:', updatedUserInfo);
          }
          
          // 如果用户是全站会员，自动切换到全站会员标签
          if (memberType === 'GLOBAL') {
            this.setData({
              membershipType: 'fullSite'
            });
          }
          
          console.log('用户档案信息更新成功:', {
            memberType: memberType,
            memberExpire: memberExpire,
            daysRemaining: daysRemaining,
            isVip: isVip
          });
        } else {
          console.log('接口返回数据格式不正确或缺少data字段');
          this.setDefaultUserProfile();
        }
      })
      .catch(err => {
        console.error('获取用户档案失败:', err);
        this.setDefaultUserProfile();
      });
  },

  /**
   * 计算会员剩余天数
   */
  calculateDaysRemaining(expireDate) {
    if (!expireDate) {
      return 0;
    }
    
    try {
      const now = new Date();
      const expire = new Date(expireDate);
      const diffTime = expire.getTime() - now.getTime();
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      
      return diffDays > 0 ? diffDays : 0;
    } catch (error) {
      console.error('计算剩余天数失败:', error);
      return 0;
    }
  },

  /**
   * 设置默认用户档案信息
   */
  setDefaultUserProfile() {
    const defaultProfile = {
      memberType: null,
      memberExpire: null
    };
    
    this.setData({
      userProfile: defaultProfile,
      memberDaysRemaining: 0,
      isVip: false
    });
    
    console.log('设置默认用户档案信息:', defaultProfile);
  },

  /**
   * 头像加载错误处理
   */
  onAvatarError(e) {
    console.log('头像加载失败:', e);
    // 设置默认头像
    this.setData({
      'userInfo.avatar': '/images/default-avatar.png'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})